<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Category model
 *
 * @subpackage	Category Module
 * @category	Modules
 * @author lethanhquang910@gmail.com
 */
class Category_m extends CI_Model {

    /**
     * Update an existing category
     * @access public
     * @param int $id The ID of the category
     * @param array $data The data to update
     * @return bool
     */
    public function update($id, $data) {
        return $this->db->where('category_id', $id)
                        ->update('category', $data);
    }

    /**
     * Callback method for validating the title
     * @access public
     * @param string $title The title to validate
     * @return mixed
     */
    public function check_title($title = '') {
        $this->db->where('slug', url_title($title));

        return $this->db->count_all_results('category') > 0;
    }

    /**
     * Insert a new category into the database via ajax
     * @access public
     * @param array $input The data to insert
     * @return int
     */
    public function insert($input = array()) {
        //Insert object to DB
        $this->db->insert('category', $input);

        //Get insert_id
        return $this->db->insert_id();
    }

    /**
     * Get all category by parent id
     * @param type $parentId
     * @return type 
     */
    public function get_all_by_parent_id($parentId) {
        return $this->db->where('parent_id', $parentId)
                        ->get('category')
                        ->result_array();
    }

    /**
     * Get all category
     * @param type $arrParams
     * @return type 
     */
    public function get_all($arrParams = NULL) {
        if ($arrParams) {
            $this->db->where($arrParams);
        }

        return $this->db->get('category')
                        ->result_array();
    }

    /**
     * Delete category by id
     * @param type $id
     * @return type 
     */
    public function delete($id) {
        return $this->db->where('category_id', $id)
                        ->delete('category');
    }
    
    /**
     * Get category tree
     * @param array $arrParams
     */
    public function get_tree($arrParams = NULL)
    {
        $arrCategory = $this->get_all($arrParams);
        
        if (sizeof($arrCategory) > 0) {
            $arrNewCategory = array();
            foreach ($arrCategory as $cate) {
                if ($cate['parent_id'] == 0) {
                    $arrNewCategory[$cate['category_id']] = $cate;
                } else {
                    $arrNewCategory[$cate['parent_id']]['child'][$cate['category_id']] = $cate;
                }
            }

            $arrCategory = $arrNewCategory;
        }
        
        return $arrCategory;
    }

}